# -*- coding:utf-8 -*-
"""
均线跟踪策略
"""
from function.interface import *
import numpy as np
import talib

class Strategy4(JyInterface):
    symbol = 'btcusdt'
    size = 1000
    period='1min'
    shortOpenPeriod = 20
    longOpenPeriod  = 40
    shortClosePeriod = 20
    longClosePeriod  = 40
    buyObsPeriod = 3
    sellObsPeriod = 3
    cash = 80
    def __init__(self, **kwargs):
        super(Strategy4, self).__init__(**kwargs)

    def cross(self, data):
        flag1 = -np.ones(len(data))
        flag2 = -np.ones(len(data))
        short = talib.SMA(data, timeperiod=self.shortOpenPeriod)
        long  = talib.SMA(data, timeperiod=self.longOpenPeriod)
        flag1[short>long] = 1
        n1 = sum(flag1[-self.buyObsPeriod:])
        short = talib.SMA(data, timeperiod=self.shortClosePeriod)
        long  = talib.SMA(data, timeperiod=self.longClosePeriod)
        flag2[short<long] = 1
        n2 = sum(flag2[-self.sellObsPeriod:])        
        return flag1[-1], flag2[-1], n1, n2  # 返回均线信号和观察值
    
    def loop(self):
        """策略部分"""
        data = self.getKline(self.symbol, self.period, self.size)
        openflag, closeflag, openSp, closeSp = self.cross(data['closes'])
        
        if openflag == 1 and openSp >= self.buyObsPeriod:
            lastprice = self.getLastPrice(self.symbol)
            orderId = self.buy(self.symbol, lastprice, self.cash/lastprice)
        elif closeflag == 1 and closeSp >= self.sellObsPeriod:
            lastprice = self.getLastPrice(self.symbol)
            position = self.getPositionSt(self.symbol)
            orderId = self.sell(self.symbol, lastprice, position)
            

if __name__ == "__main__":
    st = Strategy4(type_=1,futureOrSpot=0,appKey='e1165f79-ed2htw937',secret='bf36b118-d94ed1c08f5',passphrase='',transferId='98_41')
    st.run(st.loop)
